<template>
  <div class="home">
    <div class="keyPosition">
      <div class="phoneInput">
        <input v-model="phone" class="placeholderClass" />
      </div>
      <div class="keyboard">
        <div class="keyboardListClass" v-for="(item,index) in list" :key="index" @click="callNumber(item)">
          <div class="phoneNumberItem">
            {{ item }}
          </div>
        </div>
        <div class="keyboardListClass">
          <div class="phoneIcon">
            <!-- <van-icon name="phone" size="50" color="#00BE63" @click="hiddenKeyboard" /> -->
            <i class="iconfont icon-dialpad" style="color:#4898FF;font-size:50px;" @click="hiddenKeyboard" />
          </div>
        </div>
        <div class="keyboardListClass">
          <div class="phoneIcon">
            <van-icon name="phone" size="50" color="#00BE63" @click="call" />
          </div>
        </div>
        <div class="keyboardListClass">
          <div class="phoneIcon">
            <!-- <van-icon name="phone" size="50" color="#00BE63" @click="removeNumber()" /> -->
            <i class="iconfont icon-delete" style="color:#4898FF;font-size:75px;" @click="removeNumber" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { Dialog, Notify, Toast } from 'vant'
import aiccCallApi from '@/apiaicc/aiccCallApi'
import axios from 'axios'
import { getCookies } from '@/utils/util.js'
import qs from 'qs'

const base_url = process.env.BASE_API
export default {
    components: {
      Toast,
      Dialog,
      Notify
    },
    data() {
      return {
        list: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '0', '#'],
        phone: '',
        tokenInfo: []
      }
    },
    methods: {
      callNumber(item) {
        this.phone += item
      },
      removeNumber() {
        this.phone = this.phone.substring(0, this.phone.length - 1)
      },
      hiddenKeyboard() {
        this.$emit('hiddenKey')
      },
      call() {
        let vm = this
        if (vm.phone === "" || vm.phone === null) {
          Dialog.alert({
            title: '',
            message: '号码不能为空'
          }).then(() => {
            // on close
          })
          return
        } else { //手机
          if (!vm.validMobile(vm.phone)) {
            Dialog.alert({
              title: '',
              message: '号码不正确'
            }).then(() => {
              // on close
            })
            return
          }
        }
        let isPc = vm.checkIsPC()
        // isPc = true
        if (localStorage.getItem("isAiccUser") + "" == "true") {
          Toast.loading({
            message: '拨打中，请稍后...',
            forbidClick: true,
            overlay: true
          })
          if (isPc) { //如果是PC端
            vm.doPcCallOut(isPc)
          } else { //唤起小程序
            vm.doMobileCallout(isPc)
          }
        } else {
          if (isPc) { //如果是PC端
            Dialog.alert({
              title: '',
              message: '请在手机端使用此功能'
            }).then(() => {
              // on close
            })
          } else {
            window.location.href = `tel:${tel}`
          }

        }
      },
      doMobileCallout(isPc) {
        let vm = this
        aiccCallApi.callOut({
          customerNumber: vm.phone,
          type: isPc == true ? "pc" : "phone"
        }).then((callres) => {
          console.log('AICC获取tokenInfo成功返回信息:', callres)
          if (callres.code == 0) {
            vm.tokenInfo = callres.data
            vm.toMiniprogram()
          } else {
            Toast.clear()
            Dialog.alert({
              title: '',
              message: callres.msg
            }).then(() => {
              // on close
            })
            if (res.code == -900 && res.msg == '坐席未绑定手机号码,请先绑定手机号码') {
              this.$router.push("/seatPhone");
            }
          }
        })
      },
      // 评估申请跳转小程序
      toMiniprogram() {
        let vm = this
        axios({
          url: `${base_url}/proxy/qywx/jsdkConfig`,
          method: 'post',
          data: qs.stringify(
            // { url: 'http://wycl.autocnd.com:41080/ysc/assessManageDetail' },
            {
              url: location.href.split('?')[0],
              type: 'app'
            }, {
              encode: false
            },
          ),
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            satoken: getCookies('token'),
          },
        }).then((res) => {
          console.log('jsdkConfig:', res)
          let jsdk = res.data.data
          localStorage.setItem('jsdk', JSON.stringify(res.data.data))
          wx.agentConfig({
            corpid: jsdk.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
            agentid: jsdk.agentid, // 必填，企业微信的应用id （e.g. 1000247）
            timestamp: jsdk.timestamp, // 必填，生成签名的时间戳
            nonceStr: jsdk.nonceStr, // 必填，生成签名的随机串
            signature: jsdk.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
            jsApiList: ['launchMiniprogram'], //必填，传入需要使用的接口名称
            success: function(res) {
              console.log('agentConfig权限成功返回信息:', res)
              // wx9e482fe1abf18c87
              // appid: 'wx02e51afc29cecca4', // 需跳转的小程序appid
              wx.invoke(
                'launchMiniprogram', {
                  appid: vm.tokenInfo.appId, // 需跳转的小程序appid
                  // appid: 'wx9e482fe1abf18c87', // 测试跳转的appid
                  path: `pages/calling/calling?token=${vm.tokenInfo.token}&enterpriseId=${vm.tokenInfo.enterpriseId}&cno=${vm.tokenInfo.cno}&called_number=${vm.tokenInfo.calledNumber}&platform=${vm.tokenInfo.platform}&type=1`, // 所需跳转的小程序内页面路径及参数
                },
                function(res) {
                  Toast.clear()
                  if (res.err_msg == 'launchMiniprogram:ok') {
                    // 正常
                  } else {
                    // 错误处理
                  }
                },
              )
            },
            fail: function(res) {
              Toast.clear()
              console.log('agentConfig权限失败返回信息:', res)
              if (res.errMsg.indexOf('function not exist') > -1) {
                alert('版本过低请升级')
              }
            },
          })
        })
      },
      doPcCallOut(isPc) {
        aiccCallApi.callOut({
          customerNumber: this.phone,
          type: isPc == true ? "pc" : "phone"
        }).then((res) => {
          Toast.clear()
          if (res.code == 0) {
            Notify({
                type: 'success',
                message: '呼叫成功，请稍后'
            })
          } else {
            Dialog.alert({
              title: '',
              message: res.msg
            }).then(() => {
              // on close
            })
            if (res.code == -900 && res.msg == '坐席未绑定IP话机,请先绑定IP话机') {
              this.$router.push("/seatPhone");
            }
          }
        })
      },
      validMobile(str) {
        return /^1[3456789]\d{9}$/.test(str) || /^0[0-9-]{10,13}$/.test(str)
      },
      checkIsPC() {
        var userAgentInfo = navigator.userAgent;
        var Agents = ["Android", "iPhone",
          "SymbianOS", "Windows Phone",
          "iPad", "iPod"
        ];
        var flag = true;
        for (var v = 0; v <= Agents.length; v++) {
          if (userAgentInfo.indexOf(Agents[v]) >= 0) {
            flag = false;
            break;
          }
        }
        return flag;
      },
    },
  }
</script>
<style scoped>
  .home {
    background-color: #ffffff;
    //font-family: 'Alibaba';
    //height: calc(100vh - 60px);
    width: 100%;
  }

  .keyPosition {
    position: fixed;
    bottom: 0;
    left: 0;
  }

  .keyboard {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;

  }

  .keyboardListClass {
    width: calc(100vw / 3);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
  }

  .phoneNumberItem {
    width: 66px;
    height: 66px;
    border-radius: 50%;
    border: 1px solid #8c8c8c;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40px;
  }

  .phoneIcon {
    width: 66px;
    height: 66px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40px;
  }

  .placeholderClass {
    color: #101010;
    font-size: 40px;
    font-weight: 600;
    width: 80vw;
    text-align: center;
    direction: rtl;
  }

  .phoneInput {
    width: 100vw;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
  }
</style>
